package com.xxg.fileshand.net;

import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.xxg.fileshand.constant.Constant;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.IOException;

import retrofit2.HttpException;

/**
 * 
 * date: 2019/11/04
 * desc:
 */
public abstract class BaseSubscriber<T> implements Subscriber<BaseResponse<T>> {

    public BaseSubscriber() {
    }

    @Override
    public void onSubscribe(Subscription s) {

    }

    @Override
    public void onNext(BaseResponse<T> tBaseResponse) {

        int code = tBaseResponse.getCode();
        switch (code) {
            case Constant.Code.TimeStampError:
                onFail(tBaseResponse.getCode(), tBaseResponse.getMsg());
//                Timber.d("onNext: TimeStampError0");
                return;
            case Constant.Code.UnAuthorized:
//                Timber.d("onNext: UnAuthorized");
                onFail(tBaseResponse.getCode(), tBaseResponse.getMsg());
                return;
            case Constant.Code.OK:
//                if (tBaseResponse.isSuccess()) {
                    if (tBaseResponse.getData() != null) {
                        onSuccess(tBaseResponse.getData());
                    } else {
                        onSuccess(null);
                    }
//                    return;
//                } else {
//                    Timber.d("onNext: 发生未知错误");
//                    onFail(tBaseResponse.getStatus(), tBaseResponse.getMessage());
//                }
                return;
            default:
                //失败
//                Timber.e("onNext: UnAuthorized");
                onFail(tBaseResponse.getCode(), tBaseResponse.getMsg());
        }
    }

    @Override
    public void onError(Throwable e) {
        String errorMsg;
        if (e instanceof IOException) {
            /** 没有网络 */
            errorMsg = "Please check your network status";
        } else if (e instanceof HttpException) {
            /** 网络异常，http 请求失败，即 http 状态码不在 [200, 300) 之间, such as: "server internal error". */
            errorMsg = ((HttpException) e).response().message();
        } else if (e instanceof Exception) {
            /** 网络正常，http 请求成功，服务器返回逻辑错误 */
            errorMsg = e.getMessage();
        } else {
            /** 其他未知错误 */
            errorMsg = !TextUtils.isEmpty(e.getMessage()) ? e.getMessage() : "unknown error";
        }
//        Timber.e("error:%s", e.getMessage());
        onFail(0, errorMsg);
    }

    @Override
    public void onComplete() {
//        Timber.d("加载完毕！");
    }

    public abstract void onSuccess(@Nullable T t);

    public abstract void onFail(int code, String msg);

}
